package com.xuecheng.content.service.jobhandler;

import com.huanf.domain.MqMessage;
import com.huanf.service.MessageProcessAbstract;
import com.huanf.service.MqMessageService;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.service.CoursePublishService;
import com.xxl.job.core.context.XxlJobHelper;


import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class CoursePublishTask extends MessageProcessAbstract {

    @Resource
    CoursePublishService coursePublishService;

    @XxlJob("coursePublishJobHandler")
    public void coursePublishJobTask() {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        //执行器的序号，从0开始
        int shardTotal = XxlJobHelper.getShardTotal();
        //执行器总数
        //调用抽象类的方法执行任务
        process(shardIndex, shardTotal, "course_publish", 30, 60);

    }


    @Override
    public boolean execute(MqMessage mqMessage) {
        //从参数中拿到courseId
        Long courseId = Long.valueOf(mqMessage.getBusinessKey1());

        //向elashticsearch写索引数据
        saveCourseIndex(mqMessage,courseId);
        //向redis写缓存

        //课程静态化上传到minio
        generateCourseHtml(mqMessage,courseId);
        //任务完成后返回true
        return true;
    }

    //生成课程静态化页面并上传至文件系统
    private void generateCourseHtml(MqMessage mqMessage,Long courseId) {
        //任务幂等性处理（乐观锁）
        Long taskId = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
        int stageOne = mqMessageService.getStageOne(taskId);
        if (stageOne > 0){
            log.debug("静态页面已上窜，无需再次执行");
            return;
        }
        //生成静态化页面
        File file = coursePublishService.generateCourseHtml(courseId);
        if (file == null){
            XueChengPlusException.cast("生成静态页面失败");
        }
        //准备数据
        //生成html页面
        //上传到文件系统
        coursePublishService.uploadCourseHtml(courseId,file);
        //任务处理完成写任务状态为完成
        mqMessageService.completedStageOne(taskId);
    }

    //保存课程索引信息
    private void saveCourseIndex(MqMessage mqMessage,Long courseId) {
        //任务幂等性处理（乐观锁）
        Long taskId = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
        int stageTwo = mqMessageService.getStageTwo(taskId);
        if (stageTwo > 0){
            log.debug("课程索引信息已写入，无需再次执行");
            return;
        }
        //查询课程信息，调用搜索服务添加索引

        //任务处理完成写任务状态为完成
        mqMessageService.completedStageTwo(taskId);
    }

}
